package main

import (
	"Gin-Server-01/com/server/common"
	"Gin-Server-01/com/server/controller"
	"Gin-Server-01/com/server/core/config"
	"Gin-Server-01/com/server/core/interceptor"
	"Gin-Server-01/com/server/core/tools/times"
	"Gin-Server-01/docs"
	_ "Gin-Server-01/docs" //swag init 生成的文件夹
	"fmt"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
	"log"
	"os"
	"path/filepath"
)

// 全局配置文件
var configs = common.Configs

func init() {
	// 判断日志是否开启
	if configs.Logs.Status {
		// 组合日志文件路径
		logFileName := fmt.Sprintf("%s%s_%s.log", configs.Logs.SavePath, times.FormatDate(), configs.Logs.BasePath)

		// 创建日志目录和文件
		if err := os.MkdirAll(filepath.Dir(logFileName), 0755); err != nil {
			fmt.Printf("无法创建日志目录：%s\n", err)
			return
		}

		// 创建或打开日志文件
		file, err := os.Create(logFileName)
		if err != nil {
			fmt.Printf("无法创建日志文件：%s\n", err)
			return
		}
		//defer file.Close()

		// 设置日志输出到文件
		log.SetOutput(file)
	}
}

func main() {

	log.Println("yyds")
	// programmatically set swagger info
	docs.SwaggerInfo.Title = "XZM创建"
	docs.SwaggerInfo.Description = "这是一个示例服务器	服务器"
	docs.SwaggerInfo.Version = "1.0"
	docs.SwaggerInfo.BasePath = "/"
	docs.SwaggerInfo.Schemes = []string{"http", "https", "ws"}
	r := gin.Default()

	//配置模版-对{{很敏感
	r.LoadHTMLGlob("resources/**/*")
	r.Static("/staticPage", "resources/staticPage")
	r.Static("/css", "resources/css")
	r.Static("/js", "resources/js")

	//图片另一个
	r.Static("/staticRec", "staticRec")

	//IP限速
	r.Use(config.RateLimitMiddleware(configs))

	//跨域
	r.Use(config.CORSMiddleware())

	//拦截器
	r.Use(interceptor.AllowLoginMiddleware())

	////服务器创建ws协议-
	controller.Ws(r)
	//欢迎主页
	controller.WellComeIndexPage(r)

	//测试登录
	controller.TestLogin(r)

	run := ""
	//本地地址运行，可访问
	if configs.Server.Host == "127.0.0.1" || configs.Server.Host == "localhost" {
		run = fmt.Sprintf(":%d", configs.Server.Port)
	} else {
		run = fmt.Sprintf("%s%d", configs.Server.Host+":", configs.Server.Port)
	}

	log.Println(run)

	// 使用 Swagger 中间件
	url := ginSwagger.URL(fmt.Sprintf("http://"+"%s:%d/swagger/doc.json", common.Configs.Server.Host, common.Configs.Server.Port)) // The url pointing to API definition

	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler, url))
	r.Run(run)

}
